package com.hyd.tweet.twitter.command;

import com.hyd.tweet.twitter.DirectMessageFormatter;
import com.hyd.tweet.twitter.StatusFormatter;
import com.hyd.tweet.util.StringUtils;
import twitter4j.DirectMessage;
import twitter4j.Status;
import twitter4j.TwitterException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * (description)
 *
 * @author yiding.he
 */
public class ListCommand extends Command {

    @Override
    public List<String> processCommand() throws TwitterException {
        if (arguments.isEmpty()) {
            return Arrays.asList("——没有指定用户（me 表示自己）。");
        }

        String screenName = arguments.get(0);

        // 初始化各种列表
        List<Status> statuses = null;
        List<DirectMessage> messages = null;
        List<twitter4j.User> twitterUsers = null;

        // 根据命令查询其中的一个列表
        if (screenName.equals("me")) {
            statuses = twitter.getUserTimeline();
            
        } else if (screenName.equals("fav")) {
            statuses = twitter.getFavorites();
            
        } else if (screenName.equals("msg")) {
            messages = twitter.getDirectMessages();
            
        } else if (screenName.equals("block")) {
            twitterUsers = listBlockedTwitterUsers();
            
        } else {
            statuses = twitter.getUserTimeline(screenName);
        }

        // 将查询结果返回
        List<String> result = new ArrayList<String>();

        if (statuses != null) {
            processStatuses(screenName, statuses, result);
            
        } else if (messages != null) {
            Collections.reverse(messages);
            for (DirectMessage message : messages) {
                result.add(DirectMessageFormatter.formatDirectMessage(message));
            }
            result.add("——已列出最近收到的" + messages.size() + "条私信。");
            
        } else if (twitterUsers != null) {
            StringBuilder sb = new StringBuilder("——被您拉黑的用户列表: ");
            for (twitter4j.User tuser : twitterUsers) {
                sb.append(tuser.getScreenName()).append(", ");
            }
            result.add(StringUtils.removeEnd(sb.toString().trim(), ","));
        }

        return result;
    }

    private List<twitter4j.User> listBlockedTwitterUsers() throws TwitterException {
        return twitter.getBlocksList();
    }

    private void processStatuses(String screenName, List<Status> statuses, List<String> result) {
        Collections.reverse(statuses);

        for (Status status : statuses) {
            int rollerId = user.pushToRoller(status);
            result.add(StatusFormatter.formatStatus(twitterUser, status, rollerId));
        }

        String name = screenName.equals("fav") ? "您收藏的" : "该用户的";
        result.add("——已列出" + name + "最近" + statuses.size() + "条推。");
    }
}
